import { SettingsService, _HttpClient } from '@delon/theme';
import { Component, Inject, Optional, ViewChild, ElementRef, OnInit, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, NgForm } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { DA_SERVICE_TOKEN, TokenService } from '@delon/auth';
import { ReuseTabService } from '@delon/abc';

import { StartupService } from '@core';
import { LonginInfoDTO } from 'src/app/benshuo/model/loginInfo-dto';
import { CacheService } from '@delon/cache';

import { FormUtil } from 'src/app/benshuo/util/form/form-util';
import { parse } from 'date-fns';
import { LoginService } from 'src/app/benshuo/services/login.service';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
})
export class UserLoginComponent implements OnInit, AfterViewInit {
  /**
   * 登录表单
   */
  loginForm: FormGroup;

  /**
   * 用户账号输入控件
   */
  @ViewChild('userName', null)
  inputUserName: ElementRef;

  @ViewChild('loginDetailForm', null)
  loginDetailForm: NgForm;

  /**
   * 登录按钮的loading状态
   */
  loading = false;

  LonginInfoDTO: LonginInfoDTO = {
    account: null,
    password: null,
  };

  /**
   * 需要缓存的用户信息对象
   */
  userInfo = {
    id: '',
    name: '',
    authorities: [],
  };

  /**
   * 当前用户id
   */
  userId = '';

  loginModel = null;

  rememberMe = false;

  constructor(
    private router: Router,
    public msg: NzMessageService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private cacheService: CacheService,
    private longinService: LoginService,
    private starupService: StartupService,
    private settingService: SettingsService,
  ) {}

  ngOnInit(): void {
    this.cacheService.clear();
    this.tokenService.clear();
    this.settingService.setUser(null);
    this.settingService.setLayout(null);
    this.loginModel = this.createModel();
  }

  private createModel(): any {
    const Model = {
      userName: null,
      password: null,
    };
    return Model;
  }

  ngAfterViewInit(): void {}

  /**
   * 登录
   */
  onLogin($event: Event) {
    $event.preventDefault();
    this.cacheService.set('__user', this.userInfo, {
      type: this.rememberMe ? 's' : 'm',
    });
    if (!FormUtil.validateForm(this.loginDetailForm.form)) {
      return;
    }

    // 默认配置中对所有HTTP请求都会强制[校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
    this.loading = true;
    console.log(this.LonginInfoDTO);
    // tslint:disable-next-line: deprecation
    this.longinService.login(this.LonginInfoDTO).subscribe(
      data => {
        this.loading = false;
        if (data) {
          this.afterLogin(data);
        }
      },
      null,
      () => {
        this.loading = false;
      },
    );
  }

  afterLogin(data: any) {
    // 清空路由复用信息
    this.reuseTabService.clear();
    // 设置Token信息
    this.tokenService.set(data);
    this.longinService.findById(data.userId).subscribe(user => {
      this.userId = data.userId;
      if (user) {
        this.userInfo.id = data.userId;
        this.userInfo.name = user.name;
        this.userInfo.authorities = user.authorities;
        // 缓存用户信息
        const expire = parse(data.expires);
        this.cacheService.set('__user', this.userInfo, {
          type: this.rememberMe ? 's' : 'm',
          expire: (expire.getTime() - new Date().getTime()) / 1000,
        });
        this.starupService.load().then(() => this.router.navigate(['/']));
      }
    });
  }
}
